package com.xx.springboot.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.xx.springboot.Vo.BlogVo;
import com.xx.springboot.annotation.Log;
import com.xx.springboot.entity.*;
import com.xx.springboot.service.IBlogService;
import com.xx.springboot.service.ICategoryService;
import com.xx.springboot.service.ICommentService;
import com.xx.springboot.service.IUserService;
import com.xx.springboot.service.impl.QQAuthServiceImpl;
import com.xx.springboot.utils.FileUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xiaoxiunique
 * @since 2018-08-06
 */
@RestController
@RequestMapping("/blog")
public class BlogController extends ApiController {

    @Autowired
    private IBlogService blogService;

    @Autowired
    private IUserService userService;

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private QQAuthServiceImpl qqAuthService;

    @Autowired
    private ICommentService commentService;

    @GetMapping("/list")
    public List<Blog> list() {

        Blog condition = new Blog();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.setEntity(condition);
        wrapper.between(true, "create_time", "2018-07-01", "2018-08-06");

        List<Blog> list = blogService.list(wrapper);

        return list;
    }

    /**
     * <p>
     * 添加博客方法
     * </p>
     *
     * @param blog
     * @return
     */
    @GetMapping(value = {"/addBlog"})
    @RequiresPermissions("superAdmin:insert")
    public ResponseBo addBlog(@Validated Blog blog) throws IOException {
        try {
            blogService.save(blog);
        } catch (Exception e) {
            return ResponseBo.error(e.getMessage());
        }
        return ResponseBo.ok();
    }

    /**
     * <p>
     * 删除博客方法
     * </p>
     *
     * @param blogId
     * @return
     */
    @GetMapping(value = {"/deleteBlog", "removeBlogById"})
    public ResponseBo removeBlogById(int blogId) {
        try {
            blogService.removeById(blogId);
        } catch (Exception e) {
            return ResponseBo.error(e.getMessage());
        }
        return ResponseBo.ok();
    }


    /**
     * 通过 blogId 查询得到用户信息
     *
     * @param blogId
     * @return
     */
    @PostMapping("/getBlogById")
    @Log("查询博客")
    public ResponseBo getBlogById(Integer blogId) {

        if (blogId == null) {
            return ResponseBo.error("请输入文章Id");
        }

        BlogVo blogVo = blogService.getBlogById(blogId);

        //更新文章热度
        Blog udpBlog = new Blog();
        udpBlog.setId(Long.valueOf(blogId));
        udpBlog.setHits(Optional.ofNullable(blogVo.getHits()).orElse(1) + 1);
        blogService.updateById(udpBlog);

        ResponseBo res = commentService.list(blogId);
        res.put("obj", blogVo);

        if (blogVo != null) {
            return res;
        } else {
            return ResponseBo.error();
        }
    }


    /**
     * <p>
     * 获取得到最近博客
     * </p>
     *
     * @return
     */
    @PostMapping(value = {"/getNearBlog"})
    public ResponseBo getNearBlog() {
        /**
         * 处理发布状态和删除状态
         */
        QueryWrapper<Blog> q = new QueryWrapper<>();
        q.eq("is_delete", 0);
        q.eq("status", 1);
        q.last("limit 4");
        /**
         * 求上一周的时间的段
         */
        q.orderByDesc("create_time");

        List<Blog> blogList = blogService.list(q);
        if (blogList.size() > 0) {
            return ResponseBo.ok(blogList);
        } else {
            return ResponseBo.error("暂无最新文章");
        }
    }


    /**
     * <p>
     * admin ->  查询当前用户下的 列表 分页查询
     * </p>
     *
     * @return
     */
    @PostMapping("/findBlogListByUserId")
    public ResponseBo findBlogListByUserId(BlogVo blogVo) {
        return blogService.findBlogListByBlogVo(blogVo);
    }


    /**
     * 根据类型得到文章
     *
     * @return
     */
    @PostMapping("/getBlogListByCategory")
    public ResponseBo getBlogListByCategory(Integer categoryId, Integer pageNo, Integer pageSize) {
        List<BlogVo> blogVos = blogService.getBlogListByCate(categoryId, pageNo, pageSize);

        Category category = categoryService.getById(categoryId);

        Map<String, Object> res = new HashMap<>(2);
        res.put("list", blogVos);
        res.put("category", category);

        if (blogVos.size() > 0) {
            return ResponseBo.ok(res);
        } else {
            return ResponseBo.error();
        }
    }

    /**
     * 首页列表查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Log("访问首页数据")
    @RequestMapping("/home")
    public ResponseBo home(Integer pageNo, Integer pageSize, String searchData) {
        if (pageNo == null || pageSize == null || pageNo < 0 || pageSize <= 0) {
            return ResponseBo.error("请输入正确的分页条件!");
        }
        return blogService.getBlogList(pageNo, pageSize, searchData);
    }


    /**
     * <p>
     * admin -> 修改博客
     * </p>
     *
     * @param blog
     * @return
     */
    @Log("修改博客")
    @RequestMapping("/updateBlog")
    public ResponseBo updateBlog(Blog blog) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        try {
            if (blog.getUserId().equals(user.getId())) {
                blogService.updateById(blog);
                return ResponseBo.ok("修改成功");
            } else {
                return ResponseBo.error("非法操作");
            }

        } catch (Exception e) {
            return ResponseBo.error(e.getMessage());
        }
    }


    /**
     * 上传图片
     *
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = {"uploadImage"}, method = {RequestMethod.POST, RequestMethod.GET})
    public Map<String, Object> uploadImage(@RequestParam("image") MultipartFile file, HttpServletRequest request) throws IOException {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (!file.isEmpty()) {
            String path = request.getServletContext().getRealPath("/resource/upload/");
            File parent = new File(path);
            if (!parent.exists()) {
                parent.mkdirs();
            }
            String oldFileName = file.getOriginalFilename();
            logger.info("oldFileName");
            String fileName = FileUtils.getRandomFileName() + oldFileName.substring(oldFileName.lastIndexOf("."));
            System.out.println(fileName);
            logger.info(fileName);
            String url = "/resource/upload/" + fileName;
            file.transferTo(new File(path, fileName));
            resultMap.put("success", 1);
            resultMap.put("message", "上传成功！");
            resultMap.put("url", url);
        } else {
            logger.info("直接进入错误页面");
            resultMap.put("success", 0);
            resultMap.put("message", "上传失败！");
        }
        return resultMap;
    }


    /**
     * 第三当回调登录
     *
     * @param code
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/login")
    public void getQQCode(String code, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //根据code获取token
        String accessToken = qqAuthService.getAccessToken(code);
        //根据openId判断用户是否已经绑定过
        String openId = qqAuthService.getOpenId(accessToken);
        QueryWrapper<User> q = new QueryWrapper<>();
        q.eq("openId", openId);

        User user = userService.getOne(q);

        if (user == null) {
            //如果用户不存在，则跳转到绑定页面
            response.sendRedirect(Contains.SERVER_ADDRESS + "/login/addUser?accessToken=" + accessToken + "&openId=" + openId);

        } else {
            //如果用户已存在，则直接登录
            response.sendRedirect(Contains.SERVER_ADDRESS + "/login/qqLogin?userName=" + user.getLoginName() + "&password=" + user.getOpenId());
        }
    }

}

